package com.isoft.service.impl;

import com.isoft.entity.DfmeBoreEntity;
import com.isoft.mapper.DfmeBoreMapper;
import com.isoft.service.DfmeBoreService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeBoreServiceImpl implements DfmeBoreService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeBoreServiceImpl.class);

    @Autowired
    private DfmeBoreMapper dfmeBoreMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeBoreEntity entity) {
        processFlightData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeBoreEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeBoreEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid XML structure");
            }

            // 验证日期时间格式
            validateDateTimeFormat(entity.getMeta().getDateTime());
            if (entity.getDflt().getBoardingTime() != null) {
                validateDateTimeFormat(entity.getDflt().getBoardingTime());
            }

            processFlightData(entity);

            return "Flight boarding data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("XML processing failed", e);
            throw new RuntimeException("Failed to process XML: " + e.getMessage());
        }
    }

    private void validateDateTimeFormat(String dateTime) {
        if (dateTime == null || !dateTime.matches("\\d{14}")) {
            throw new IllegalArgumentException("Invalid date time format, expected yyyyMMddHHmmss, got: " + dateTime);
        }
    }

    private void processFlightData(DfmeBoreEntity entity) {
        // 检查记录是否存在
        int count = dfmeBoreMapper.countMeta(
                entity.getMeta().getSequenceNumber(),
                entity.getMeta().getType(),
                entity.getMeta().getSubType()
        );

        if (count > 0) {
            // 更新元数据
            dfmeBoreMapper.updateMeta(entity);
        } else {
            // 插入元数据
            dfmeBoreMapper.insertMeta(entity);
        }

        // 插入或更新航班基础信息
        dfmeBoreMapper.upsertFlightBase(entity);

        // 插入或更新登机时间信息
        if (entity.getDflt().getBoardingTime() != null && !entity.getDflt().getBoardingTime().isEmpty()) {
            dfmeBoreMapper.insertBoardingTime(entity);
        }

        // 新增：插入航班异常信息到FLIGHT_IRREGULARITY表
        dfmeBoreMapper.insertIrregularity(entity);
    }
}